package com.nowcoder.community.controller;

import com.nowcoder.community.contant.Topic;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.service.FollowService;
import com.nowcoder.community.utils.CommunityUtils;
import com.nowcoder.community.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/follow")
public class FollowController {
    @Autowired
    private FollowService followService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    @PostMapping
    @ResponseBody
    public String follow(int entityType, int entityId){
        User user = hostHolder.getUser();
        if (user == null){
            throw new RuntimeException("用户未登录");
        }

        int followStatus = followService.follow(user.getId(), entityType, entityId);
        if (followStatus == 1){
            Event event = new Event()
                    .setTopic(Topic.FOLLOW)
                    .setUserId(hostHolder.getUser().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityId);
            eventProducer.fireEvent(event);
        }
        return CommunityUtils.getJsonString(200, "操作成功");
    }
}
